/**
 * @desc 打字机效果
 * @param { object } options 配置项
 * @param { string } options.text 完整文本
 * @param { number } options.speed 每个字符输出的间隔时间
 * @param { boolean } options.infinite 无限循环模式
 * @param { function } options.renderText 字符每次渲染时调用
 * @param { function } options.onComplete 字符渲染完成时调用
 *
 */
export class Typewriter {
  constructor(options = {}) {
    // 初始化配置
    this.outputText = '' // 输出文字
    this.text = options.text || ''
    this.speed = options.speed || 50 // 字符间隔时间(ms)
    this.infinite = options.infinite || false //
    this.renderText = options.renderText // 渲染文字
    this.onComplete = options.onComplete || function () {}

    // 运行时状态
    this.currentIndex = 0
    this.isDeleting = false
    this.timeoutId = null
  }

  start() {
    this.type()
  }

  type() {
    const fullText = this.text
    // 计算当前显示文本
    let currentText = fullText.substring(0, this.currentIndex)
    if (this.isDeleting) {
      currentText = currentText.slice(0, -1)
    }

    // 更新显示内容
    this.outputText += currentText
    this.renderText(currentText, this.outputText)

    // 控制打字速度
    let typeSpeed = this.speed
    if (this.isDeleting) {
      typeSpeed /= 2 // 回退速度加快
    }

    // 判断状态变化
    if (!this.isDeleting && this.currentIndex === fullText.length) {
      if (this.infinite) {
        typeSpeed = 1000 // 暂停1秒后开始删除
        this.isDeleting = true
      } else {
        this.onComplete()
        return
      }
    } else if (this.isDeleting && currentText === '') {
      this.isDeleting = false
      this.currentIndex = 0
      if (!this.infinite) return
    } else {
      this.currentIndex += this.isDeleting ? -1 : 1
    }

    // 递归调用
    this.timeoutId = setTimeout(() => this.type(), typeSpeed)
  }

  // 动态更新文本
  updateText(newText) {
    clearTimeout(this.timeoutId)
    this.text = newText
    this.currentIndex = 0
    this.isDeleting = false
    this.start()
  }

  // 销毁实例
  destroy() {
    clearTimeout(this.timeoutId)
  }
}

export const typed = (text, options) => {
  const renderText = options.renderText || (() => {})
  const onComplete = options.onComplete || (() => {})
  new Typewriter({
    // text: 'Hello, 这是原生JavaScript实现的打字机效果!\n支持多行文本和自动换行。',
    text,
    speed: 10,
    infinite: false,
    renderText,
    onComplete
  }).start()
}
